﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using Microsoft.Services.Clab.UI.Mvvmc.Properties;

namespace Microsoft.Services.Clab.UI.Mvvmc.Composition
{
    [Export(typeof(IControllerFactory))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class MefControllerFactory : ControllerFactoryBase
    {
        private CompositionContainer container;

        public MefControllerFactory(CompositionContainer container)
        {
            this.container = container;
        }

        protected override IController CreateControllerInstance(string logicalName, object initParameters)
        {
            var exportDef = this.container.GetExports<IController, IControllerExportMetadata>().SingleOrDefault(e => e.Metadata.LogicalName == logicalName);
            if (exportDef != null)
            {
                return exportDef.Value;
            }
            else
            {
                throw new InvalidOperationException(Resources.LogicalNameNotFoundInMefContainer.FormatEx(logicalName));
            }
        }
    }
}
